let app = getApp()
const db = wx.cloud.database({env: app.globalData.CLOUD_ENV})
const DBClassify = db.collection('db_classifys')
const DBInterview = db.collection('db_topic')
let d = null
Page({
  /**
   * 页面的初始数据
   */
  data: {
    classifys:[],
    array: [],
    columns: [
      'h5', 
      'java', 
      '嵌入式', 
      'php', 
      'python',
      '网络工程'
    ],
    num: 0,
    type: 'h5',
    index: 0,
    q: '',
    a: '',
    text: '',
    topic_code: ''
  },
  bindPickerChange2(e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let num = e.detail.value;
    let type = this.data.columns[num];
    if(this.data.classifys.length ==0) return;
    let arr = this.data.classifys.filter(item => {
        // if(item.type == type){
          return item.type == type
        // }
    })
    let newArr = arr.map(item=> item.text)
    // console.log('xx-',arr)
    // console.log('xx-',type,newArr[0])
    this.setData({
      num: num,
      type: type,
      text: newArr[0],
      array: newArr 
    })
  },
   // 分类列表
   async listClassifyFn() {
    let res = await DBClassify.where({}).count()
    let count = res.total;
    let all = [];
    for(let i = 0 ; i < count ; i+= 20){
        await DBClassify.where({}).skip(i).get()
        .then(
          content => {
            // console.log('3.0', content)
            let {data} = content;
            if(data.length!=0){
              all = all.concat(data)
            }
          }
        )
    }

    let type = this.data.type
    let arr = all.map(item => {
        if(item.type == type){
          return item.text
        }
    })
    this.setData({
      classifys: all,
      array: arr
    })
  },
  bindPickerChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
      text: this.data.array[e.detail.value]
    })
  },
  addInputQ(e) {
    let text = e.detail.text;
    this.setData({
      q: text
    })
  },
  addInputA(e) {
    let text = e.detail.text;
    this.setData({
      a: text
    })
  },
  // 可输入演示代码
  addInputFunc(e){
    let v =e.detail.value;
    if(v.length != ''){
      this.setData({
        topic_code: v
      })
    }else {
      this.setData({
        topic_code: ''
      })
    }
  },
  // 点击提交
  addTopicFn() {
    let a = this.data.a;
    let q = this.data.q;
    let text = this.data.text;
    let type = this.data.type;
    let topic_code = this.data.topic_code;
    // console.log({a,q,text})
    let create_time = new Date()
    let openid = wx.getStorageSync('openid')
    if(a == '' || q == '') {
      wx.showToast({
        title: '输入框不能为空。',
        icon: 'none'
      })
      return;
    }
    let option = {
      a,
      q,
      text,
      topic_code
    };
    // let that = this;
    if (openid) {
      if (d != null) return;
      d = setTimeout(async () => {
        // 检测敏感词
        wx.cloud.callFunction({
          name: 'msgsec',
          data: {
            content: JSON.stringify(option),
            openid
          },
          success(res) {
            let {
              result: {
                errCode,
                errMsg
              }
            } = res;
            // console.log('检测结果:',res);//  errCode == 0 表示文本正常
            if (errCode == 0) {
              // 添加题目
              DBInterview.add({
                  data: {
                    openid,
                    a,
                    q,
                    text,
                    type,
                    create_time,
                    topic_code
                  }
                })
                .then(
                  content => {
                    // console.log('--->', content)
                    d=null;
                    let {
                      errMsg
                    } = content;
                    if (errMsg == "collection.add:ok") {
                      wx.showToast({
                        title: '发布成功。',
                        icon: 'none'
                      })
                      // 设置分类数量
                      DBInterview.where({text}).count().then(
                        async rows=>{
                          // console.log({rows})
                          let {total,errMsg} = rows;
                          // console.log("total:",total)
                          if(errMsg == "collection.count:ok") {
                              // if(!isNaN(total)){
                                  // console.log("--->total:",total)
                                 await  DBClassify.where({text}).update({data:{total}}).then(
                                    res=>{
                                      // console.log('结果',{res})
                                    }
                                  )
                              // }
                          }
                        }
                      )

                      let delay = setTimeout(() => {
                        // 跳转...
                        // wx.redirectTo({
                        //   url: '../list/list',
                        // })
                        clearTimeout(delay)
                        delay = null;
                      }, 300)
                    } else {
                      wx.showToast({
                        title: '发布失败。',
                        icon: 'none'
                      })
                    }
                  }
                )
            } else {
              if (errMsg != "openapi.security.msgSecCheck:ok") {
                wx.showToast({
                  title: '您输入的内容包含敏感词哦。',
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: `${errMsg},${errCode}`,
                  icon: 'none'
                })
              }
            }
          }
        })
      }, 300)
    } else {
      wx.navigateTo({
        url: '../../../user/login/login',
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.listClassifyFn()
    // DBInterview.where({text:'htmlcss'}).remove()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})